package spm.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * The class is responsible for creating, returning and closing the
 * <code>SessionFactory</code> object.
 * 
 * @author Evgeny Ryzhkov
 * 
 * $Id: HibernateManager.java 19 2006-12-05 15:27:07Z evgeny.ryzhkov $
 */
public class HibernateManager {

	private static final Log log = LogFactory.getLog(HibernateManager.class);

	private static HibernateManager hibernateManager = null;

	private SessionFactory sessionFactory = null;

	/**
	 * Returns the instance of the SessionFactory.
	 * 
	 * @return the SessionFactory
	 */
	public synchronized static HibernateManager getInstance(boolean isCreate) {
		if (hibernateManager == null) {
			hibernateManager = new HibernateManager(isCreate);
			log.debug("The hibernateManager is null - "
					+ "new instance is created.");
		}
		log.debug("The HibernateManager instance is returned.");
		return hibernateManager;
	}

	/**
	 * Returns the SessionFactory.
	 * 
	 * @return the SessionFactory
	 */
	public SessionFactory getSessionFactory() {
		log.debug("The sessionFactory is returned.");
		return sessionFactory;
	}

	/**
	 * Closes the SessionFactory.
	 */
	public void destroySessionFactory() {
		if (sessionFactory != null) {
			sessionFactory.close();
			log.debug("The sessionFactory is closed.");
		} else {
			log.debug("The sessionFactory is NULL and could not be closed!");
		}
	}

	/**
	 * Constructor.
	 * 
	 * @param isCreate
	 */
	private HibernateManager(boolean isCreate) {
		try {
			Configuration configuration = new Configuration();
			log.debug("The Configuration instance is created.");
			configuration = configuration.configure();
			log.debug("The Configuration instance is configured.");
			// If isCreate = true the hibernate has to create schema
			// in the database.
			if (isCreate) {
				configuration.setProperty("hibernate.hbm2ddl.auto", "create");
				log.debug("The hibernate.hbm2ddl.auto property "
						+ "is set to CREATE.");
			} else {
				configuration.setProperty("hibernate.hbm2ddl.auto", "");
				log.debug("The hibernate.hbm2ddl.auto property "
						+ "is set to EMPTY.");
			}
			sessionFactory = configuration.buildSessionFactory();
			log.debug("The sessionFactory is created and initialized.");
		} catch (Throwable t) {
			log.error("SessionFactory creation failed: " + t);
			throw new ExceptionInInitializerError(t);
		}
	}
}
